/**
 * 小程序权限管理工具
 * 用于处理摄像头、麦克风等权限请求
 */

import Taro from '@tarojs/taro'

export interface PermissionResult {
  granted: boolean
  scope: string
  message?: string
}

/**
 * 请求单个权限
 */
export const requestPermission = async (scope: string): Promise<PermissionResult> => {
  try {
    await Taro.authorize({ scope })
    return { granted: true, scope }
  } catch (error: any) {
    console.log(`权限 ${scope} 被拒绝:`, error)
    
    // 显示权限说明弹窗
    const modalResult = await Taro.showModal({
      title: '权限申请',
      content: getPermissionDescription(scope),
      confirmText: '去设置',
      cancelText: '取消'
    })
    
    if (modalResult.confirm) {
      // 打开设置页面
      const settingResult = await Taro.openSetting()
      if (settingResult.authSetting[scope]) {
        return { granted: true, scope }
      }
    }
    
    return { 
      granted: false, 
      scope, 
      message: `用户拒绝了 ${scope} 权限` 
    }
  }
}

/**
 * 批量请求权限
 */
export const requestMultiplePermissions = async (scopes: string[]): Promise<PermissionResult[]> => {
  const results: PermissionResult[] = []
  
  for (const scope of scopes) {
    const result = await requestPermission(scope)
    results.push(result)
    
    // 如果某个权限被拒绝，可以选择是否继续
    if (!result.granted) {
      console.warn(`权限 ${scope} 被拒绝，继续请求其他权限`)
    }
  }
  
  return results
}

/**
 * 检查权限状态
 */
export const checkPermissionStatus = async (scope: string): Promise<boolean> => {
  try {
    const setting = await Taro.getSetting()
    return !!setting.authSetting[scope]
  } catch (error) {
    console.error('检查权限状态失败:', error)
    return false
  }
}

/**
 * 获取权限描述
 */
const getPermissionDescription = (scope: string): string => {
  const descriptions: Record<string, string> = {
    'scope.camera': '需要摄像头权限进行视频通话和拍照功能',
    'scope.record': '需要麦克风权限进行语音消息和视频通话',
    'scope.album': '需要相册权限选择照片进行魔镜测脸分析',
    'scope.userLocation': '需要位置权限获取附近医院信息'
  }
  
  return descriptions[scope] || `需要 ${scope} 权限才能使用相关功能`
}

/**
 * 视频通话权限检查
 */
export const checkVideoCallPermissions = async (): Promise<{
  camera: boolean
  record: boolean
  allGranted: boolean
}> => {
  const [cameraResult, recordResult] = await Promise.all([
    checkPermissionStatus('scope.camera'),
    checkPermissionStatus('scope.record')
  ])
  
  return {
    camera: cameraResult,
    record: recordResult,
    allGranted: cameraResult && recordResult
  }
}

/**
 * 请求视频通话权限
 */
export const requestVideoCallPermissions = async (): Promise<boolean> => {
  const results = await requestMultiplePermissions(['scope.camera', 'scope.record'])
  
  const cameraGranted = results.find(r => r.scope === 'scope.camera')?.granted || false
  const recordGranted = results.find(r => r.scope === 'scope.record')?.granted || false
  
  if (!cameraGranted || !recordGranted) {
    Taro.showToast({
      title: '需要摄像头和麦克风权限才能进行视频通话',
      icon: 'none',
      duration: 3000
    })
    return false
  }
  
  return true
}

/**
 * 权限调试信息
 */
export const getPermissionDebugInfo = async (): Promise<{
  allPermissions: Record<string, boolean>
  videoCallReady: boolean
  recommendations: string[]
}> => {
  const scopes = ['scope.camera', 'scope.record', 'scope.album', 'scope.userLocation']
  const allPermissions: Record<string, boolean> = {}
  
  for (const scope of scopes) {
    allPermissions[scope] = await checkPermissionStatus(scope)
  }
  
  const videoCallReady = allPermissions['scope.camera'] && allPermissions['scope.record']
  
  const recommendations: string[] = []
  if (!allPermissions['scope.camera']) {
    recommendations.push('需要摄像头权限进行视频通话')
  }
  if (!allPermissions['scope.record']) {
    recommendations.push('需要麦克风权限进行语音通话')
  }
  if (!allPermissions['scope.album']) {
    recommendations.push('需要相册权限选择照片')
  }
  
  return {
    allPermissions,
    videoCallReady,
    recommendations
  }
}
